﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SVNUG.Presentations.NoSql.Business
{
    public static class CustomerRepository
    {
        public static void StoreCustomer(this Raven.Client.IDocumentSession session, Customer customer)
        {
            session.Store(customer, customer.CustomerId.ToString());

            //session.SaveChanges();
        }
        public static void RemoveCustomer(this Raven.Client.IDocumentSession session, Customer customer)
        {
            customer = session.TryFindCustomer(customer.CustomerId);

            if (customer != null)
            {
                session.Delete<Customer>(customer);
            }

            //session.SaveChanges();
        }
        public static Customer TryFindCustomer(this Raven.Client.IDocumentSession session, Guid customerId)
        {
            return session.Load<Customer>(customerId.ToString());
        }
        public static List<Customer> FindAllCustomers(this Raven.Client.IDocumentSession session)
        {
            return session.Query<Customer>().ToList();
        }

        public static Customer TryFindCustomerByLastName(this Raven.Client.IDocumentSession session, String lastName)
        {
            var result = (from a in session.Query<Customer>()
                          where a.LastName == lastName
                          select a).FirstOrDefault();

            return result;
        }

        public static void StoreCustomer(this RavenDbContext documentStore, Customer customer)
        {
            using (var session = documentStore.Store.OpenSession())
            {
                session.StoreCustomer(customer);

                session.SaveChanges();
            }
        }
        public static void RemoveCustomer(this RavenDbContext documentStore, Customer customer)
        {
            using (var session = documentStore.Store.OpenSession())
            {
                session.RemoveCustomer(customer);

                session.SaveChanges();
            }
        }
        public static Customer TryFindCustomer(this RavenDbContext documentStore, Guid customerId)
        {
            using (var session = documentStore.Store.OpenSession())
            {
                return session.TryFindCustomer(customerId);
            }
        }
        public static List<Customer> FindAllCustomers(this RavenDbContext documentStore)
        {
            using (var session = documentStore.Store.OpenSession())
            {
                return session.FindAllCustomers();
            }
        }
        public static Customer TryFindCustomerByLastName(this RavenDbContext documentStore, String lastName)
        {
            using (var session = documentStore.Store.OpenSession())
            {
                return session.TryFindCustomerByLastName(lastName);
            }
        }
    }
}
